package com.xqboss.framework.web.service;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import javax.servlet.http.HttpServletRequest;

import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import com.xqboss.common.constant.CacheConstants;
import com.xqboss.common.constant.Constants;
import com.xqboss.common.core.domain.model.LoginUser;
import com.xqboss.common.core.redis.RedisCache;
import com.xqboss.common.utils.ServletUtils;
import com.xqboss.common.utils.StringUtils;
import com.xqboss.common.utils.ip.AddressUtils;
import com.xqboss.common.utils.ip.IpUtils;
import com.xqboss.common.utils.uuid.IdUtils;
import eu.bitwalker.useragentutils.UserAgent;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

/**
 * token验证处理
 *
 * admin： f69a480c-abd4-4ca5-9242-46d5c4a9f190
 *
 * @author Administrator
 */
@Component
public class TokenService {
    // 令牌自定义标识
    @Value("${token.header}")
    private String header;

    // 令牌秘钥
    @Value("${token.secret}")
    private String secret;

    // 令牌有效期（默认30分钟）
    @Value("${token.expireTime}")
    private int expireTime;

    protected static final long MILLIS_SECOND = 1000;

    protected static final long MILLIS_MINUTE = 60 * MILLIS_SECOND;

    private static final Long MILLIS_MINUTE_TEN = 20 * 60 * 1000L;

    @Autowired
    private RedisCache redisCache;

    /**
     * 获取用户身份信息
     *
     * @return 用户信息
     */
    public LoginUser getLoginUser(HttpServletRequest request) {
        // 获取请求携带的令牌
        String token = getToken(request);
        return getLoginUser(token);
    }

    public LoginUser getLoginUser(String token){
        if (StringUtils.isNotEmpty(token)) {
            try {
                Claims claims = parseToken(token);
                // 解析对应的权限以及用户信息
                String uuid = (String) claims.get(Constants.LOGIN_USER_KEY);
                String userid = (String) claims.get(Constants.JWT_USERID);
                String userKey = getTokenKey(String.valueOf(userid));
                LoginUser user = redisCache.getCacheObject(userKey);
                if (ObjUtil.isNull(user) || !StrUtil.equals(uuid, user.getToken())) {
                    return null;
                }
                return user;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    /**
     * 设置用户身份信息
     */
    public void setLoginUser(LoginUser loginUser) {
        if (StringUtils.isNotNull(loginUser) && StringUtils.isNotEmpty(loginUser.getToken())) {
            refreshToken(loginUser);
        }
    }

    /**
     * 删除用户身份信息
     */
    public void delLoginUser(String token) {
        if (StringUtils.isNotEmpty(token)) {
            String userKey = getTokenKey(token);
            redisCache.deleteObject(userKey);
        }
    }

    /**
     * 创建令牌
     *
     * @param loginUser 用户信息
     * @return 令牌
     */
    public String createToken(LoginUser loginUser) {
        String token = IdUtils.fastUUID();
        loginUser.setToken(token);
        setUserAgent(loginUser);
        refreshToken(loginUser);

        Map<String, Object> claims = new HashMap<>();
        claims.put(Constants.LOGIN_USER_KEY, token);
        claims.put(Constants.JWT_USERID, String.valueOf(loginUser.getUserId()));
        return createToken(claims);
    }

    /**
     * 验证令牌有效期，相差不足20分钟，自动刷新缓存
     *
     * @param loginUser
     * @return 令牌
     */
    public void verifyToken(LoginUser loginUser) {
        long expireTime = loginUser.getExpireTime();
        long currentTime = System.currentTimeMillis();
        if (expireTime - currentTime <= MILLIS_MINUTE_TEN) {
            refreshToken(loginUser);
        }
    }

    /**
     * 刷新令牌有效期
     *
     * @param loginUser 登录信息
     */
    public void refreshToken(LoginUser loginUser) {
        loginUser.setLoginTime(System.currentTimeMillis());
        loginUser.setExpireTime(loginUser.getLoginTime() + expireTime * MILLIS_MINUTE);
        // 根据uuid将loginUser缓存
        String userKey = getTokenKey(String.valueOf(loginUser.getUserId()));
        redisCache.setCacheObject(userKey, loginUser, expireTime, TimeUnit.MINUTES);
    }

    /**
     * 设置用户代理信息
     *
     * @param loginUser 登录信息
     */
    public void setUserAgent(LoginUser loginUser) {
        UserAgent userAgent = UserAgent.parseUserAgentString(ServletUtils.getRequest().getHeader("User-Agent"));
        String ip = IpUtils.getIpAddr();
        loginUser.setIpaddr(ip);
        loginUser.setLoginLocation(AddressUtils.getRealAddressByIP(ip));
        loginUser.setBrowser(userAgent.getBrowser().getName());
        loginUser.setOs(userAgent.getOperatingSystem().getName());
    }

    /**
     * 从数据声明生成令牌
     *
     * @param claims 数据声明
     * @return 令牌
     */
    private String createToken(Map<String, Object> claims) {
        String token = Jwts.builder()
                .setClaims(claims)
                .signWith(SignatureAlgorithm.HS512, secret).compact();
        return token;
    }

    /**
     * 从令牌中获取数据声明
     *
     * @param token 令牌
     * @return 数据声明
     */
    private Claims parseToken(String token) {
        return Jwts.parser()
                .setSigningKey(secret)
                .parseClaimsJws(token)
                .getBody();
    }

    /**
     * 从令牌中获取用户名
     *
     * @param token 令牌
     * @return 用户名
     */
    public String getUsernameFromToken(String token) {
        Claims claims = parseToken(token);
        return claims.getSubject();
    }

    /**
     * 从令牌中获取用户id
     *
     * @param token 令牌
     */
    public String getUseridFromToken(String token) {
        Claims claims = parseToken(token);
        Object obj = claims.get(Constants.JWT_USERID);
        return obj!=null?(String)obj:null;
    }

    /**
     * 获取请求token
     *
     * @param request
     * @return token
     */
    private String getToken(HttpServletRequest request) {
        String token = request.getHeader(header);
        if (StringUtils.isNotEmpty(token) && token.startsWith(Constants.TOKEN_PREFIX)) {
            token = token.replace(Constants.TOKEN_PREFIX, "");
        }
        return token;
    }

    private String getTokenKey(String uuid) {
        return CacheConstants.LOGIN_TOKEN_KEY + uuid;
    }

    /**
     * 用户上下线状态更新
     *
     * @param userId 用户id
     * @param status 用户在线状态（true-上线 false-下线）
     */
    public void setOnlineStatus(String userId, boolean status) {
        String redisCacheKey = CacheConstants.IS_ONLINE +userId;
        redisCache.setCacheObject(redisCacheKey, status);
        //删除消息推送弹窗关闭设定
        redisCache.deleteObject(CacheConstants.KEY_USER_MSG_PUSH_CLOSE_TIME+userId);
        //数据库，更改用户在线状态为上线
        redisCache.publish("WS:user-online", JSONUtil.toJsonStr(MapUtil.builder().put("userId",userId).put("isOnline",status).build()));
    }

    /**
     * 获取用户实时在线状态
     *
     * @param userId 用户id
     * @return true-实时在线
     */
    public Boolean getOnlineStatus(String userId) {
        String redisCacheKey =CacheConstants.IS_ONLINE +userId;
        Object isOnline = redisCache.getCacheObject(redisCacheKey);
        return isOnline != null?(Boolean) isOnline:false;
    }

    /**
     *
     *{"@type":"com.xqboss.common.core.domain.model.LoginUser","browser":"Chrome 12","deptId":103L,"expireTime":1707281615240,"ipaddr":"171.213.56.224","loginLocation":"XX XX","loginTime":1706676815240,"nickName":"管理员","os":"Windows 10","permissions":Set["*:*:*"],"token":"27e49d00-3e13-4b21-8f8e-e1a84c2abf9f","user":{"admin":true,"avatar":"/profile/avatar/2023/08/28/blob_20230828153225A001.png","birthday":"","channel":1,"createBy":"admin","createTime":"2023-07-25 17:33:26","delFlag":"0","dept":{"children":[],"deptId":103L,"params":{"@type":"java.util.HashMap"}},"deptId":103L,"email":"","freeOpenBox":0,"hidden":true,"identityRankId":1L,"loginDate":"2024-01-30 09:49:15","loginIp":"171.213.57.181","nickName":"管理员","params":{"@type":"java.util.HashMap"},"password":"$2a$10$hwvkE0by2Og9O46o/1FriOou2axRxmXv3lQSxraVYtBNZZFlBIBOy","phonenumber":"admin","remark":"管理员","roles":[{"admin":true,"dataScope":"1","deptCheckStrictly":false,"flag":false,"menuCheckStrictly":false,"params":{"@type":"java.util.HashMap"},"roleId":1L,"roleKey":"admin","roleName":"超级管理员","roleSort":1,"status":"0"}],"sex":"1","status":"0","userId":1L,"userName":"admin"},"userId":1L,"username":"admin"}
     * @param args
     */
    public static void main(String[] args) {
        Map<String, Object> claims = new HashMap<>();
        claims.put(Constants.LOGIN_USER_KEY, "27e49d00-3e13-4b21-8f8e-e1a84c2abf9f");
        claims.put(Constants.JWT_USERID, "1");
        String token = Jwts.builder()
                .setClaims(claims)
                .signWith(SignatureAlgorithm.HS512, "KGE6GZmCZJuETQKsWXQdg7g5ftONselJ")
                .compact();
        System.out.println(token);
    }
}
